﻿// Written by Dale J Williams.
// Licensed under MPL 1.1 unless otherwise specified. 
// http://www.mozilla.org/MPL/MPL-1.1.html

package engineDJW.load {
	
	import engineDJW.interfaces.ILoadable;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	
	/**
	 * ...
	 * @author Dale J Williams
	 */
	public class DisplayLoader extends EventDispatcher implements ILoadable {
		
		private var _loader			:Loader;
		private var _url			:String;
		private var _content		:DisplayObject;
		private var _loadPercent	:Number;
		private var _loadCompleted	:Boolean;
		private var _name			:String;
		
		public function DisplayLoader($url:String=null) {
			_url = $url;
			init();
		}
		
		private function init():void {
			_loader = new Loader();
			_loadPercent = 0;
		}
		
		public function load($url:String=null):void {
			if ($url) _url = $url;
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadError);
			addEventListener(Event.ENTER_FRAME, loadMonitor);
			_loader.load(new URLRequest(_url));
		}
		
		private function loadMonitor(e:Event):void {
			_loadPercent = _loader.contentLoaderInfo.bytesLoaded / _loader.contentLoaderInfo.bytesTotal;
		}
		
		private function loadComplete(e:Event):void {
			removeEventListener(Event.ENTER_FRAME, loadMonitor);
			_content = _loader.contentLoaderInfo.content;
			_loadPercent = 1;
			_loadCompleted = true;
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		private function loadError(e:Event):void {
			dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, true, true, "Could not find content: " + _url));
		}		
		
		public function get url():String { return _url; }		
		public function set url(value:String):void {
			_url = value;
		}
		
		public function get content():DisplayObject { return _content; }
		
		public function get loadPercent():Number { return _loadPercent; }
		
		public function get loadCompleted():Boolean { return _loadCompleted; }
		
		public function get name():String { return _name; }		
		public function set name(value:String):void {
			_name = value;
		}
		
	}
	
}